package com.jishuo.nontax.bfc.tlq;

import com.jishuo.base.config.NonTaxConfig;
import io.github.admin4j.http.util.HttpJsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
import javax.jms.TextMessage;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * Jms 消息发送
 * 
 */
@Slf4j
@Service
public class JmsSender {

    @Resource(name = "jmsQueueTemplate")
    private JmsTemplate jmsTemplate;

    @Resource
    private NonTaxConfig nonTaxConfig;
    @Resource
    private BackMessageService backMessageService;

    public String sendData(final String quneneName, final String message, final String sn) {
        if (nonTaxConfig.DebugType == 0) {
            return this.sendData_tlq(quneneName, message);
        } else if (nonTaxConfig.DebugType == 2) {
            return this.sendData_http(quneneName, message);
        } else {
            if (sn != null) {
                backMessageService.setMsg(sn);
            }
            return "";
        }
    }

    /**
     * 发送消息
     * @param quneneName 队列名称
     * @param message 消息内容
     */
    public String sendData_tlq(final String quneneName, final String message) {
        try{
            log.info("使用tlq发送消息，quneneName=" + quneneName);
            jmsTemplate.send(quneneName, new MessageCreator() {
                public Message createMessage(Session session) throws JMSException {
                    TextMessage msg = session.createTextMessage();
                    msg.setStringProperty("message_id", UUID.randomUUID().toString());
                    msg.setText(message);
                    return msg;
                }
            });
            return "";//FileUtil.createLogFile(quneneName+message, "1");
        }catch(Exception e){
            log.info(quneneName+"发送失败"+e.toString(), e);
            return null;
        }
    }

    @Async("publicThreadPool")
    public String sendData_http(final String quneneName, final String message) {
        try {
            Thread.sleep(1000);
            Map<String, Object> body = new HashMap<>();
            body.put("data", message);
            HttpJsonUtil.postForm(nonTaxConfig.CzsysDebug, body);

            return "";
        } catch (Exception e) {
            log.info("Http发送消息失败。", e);
            return null;
        }
    }
}
